/*
 * relative     : \src\hooks\useSearch.ts
 * Author       : 郭鹏超
 * Date         : 2025-01-10 09:58
 * LastEditors  : 郭鹏超
 * LastEditTime : 2025-02-20 18:24
 * Description  :模糊查询
 * CodeIterationRecord:
 */

import Fuse from "fuse.js";
import { pinyin } from "pinyin-pro";
import type { IFuseOptions, Expression } from "fuse.js";
const useSearch = <T>() => {
  const searchFuseDefaultOptions = ref<IFuseOptions<T>>({
    keys: [], // 指定要搜索的字段，可以是字符串或对象
    threshold: 0.2, // 设置模糊匹配的阈值，值越低匹配越严格
    includeMatches: false, // 是否在结果中包含匹配的字符索引
    includeScore: false, // 是否在结果中包含匹配的分数
    findAllMatches: false, // 是否继续查找所有匹配，即使已经找到完美匹配
    shouldSort: true // 是否对结果进行排序
    // distance: 0 // 设置模糊匹配的距离，0 表示完全匹配
  });
  const fuse = ref<Fuse<T>>();
  const searchData = ref<T[]>([]);
  /**
   * @description: 初始化模糊查询
   * @param isSearchData
   * @param searchFuseOptions
   * @return
   */
  const newSearchFuse = (isSearchData: T[], searchFuseOptions: IFuseOptions<T> = {}) => {
    const isSearchFuseOptions = Object.assign(searchFuseDefaultOptions.value, searchFuseOptions);
    searchData.value = isSearchData ?? [];
    fuse.value = new Fuse(isSearchData, isSearchFuseOptions);
  };
  /**
   * @description: 模糊查询
   * @param searchValue
   * @return
   */
  const searchFuse = (searchValue: string | Expression | undefined): T[] => {
    if (!fuse.value) {
      showMessage("error", "未初始化查询！");
      return searchData.value as T[];
    }
    if (!searchValue) {
      return searchData.value as T[];
    }
    return fuse.value.search(searchValue).map((item: any) => item.item) as T[];
  };

  /**
   * @description: 获取汉字简拼
   * @param chineseString
   * @return
   */
  const convertToSimplifiedSpelling = (chineseString: string) => {
    if (!chineseString) {
      return "";
    }
    return pinyin(chineseString, { pattern: "first", toneType: "none" }).replace(/\s+/g, "");
  };
  return { fuse, newSearchFuse, searchFuse, convertToSimplifiedSpelling };
};
export { useSearch };
